<!--订单管理-->
<template>
  <div>
    <div class="inquire">
      <span class="m-l-10">{{ $t('mall.status') }}</span>
      <el-select
        v-model="data.orderStatus"
        :placeholder="$t('om.AllOrderStatus')"
        size="default"
        style="width: 130px; margin-left: 12px"
        clearable
      >
        <el-option
          v-for="item in data.orderStatusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model="data.serial"
        style="width: 240px; margin-left: 12px"
        :placeholder="$t('mall.enter_order_number')"
      />
      <span style="margin-left: 12px">{{ $t('om.OrderDate') }}</span>
      <el-date-picker
        style="margin-left: 12px"
        v-model="dateRange"
        value-format="YYYY-MM-DD"
        type="daterange"
        range-separator="-"
        :start-placeholder="$t('om.Startdate')"
        :end-placeholder="$t('om.Enddate')"
      />
      <el-button style="margin-left: 10px" type="primary" @click="inquireOrderData">{{
        $t('om.Search')
      }}</el-button>
      <el-button style="margin-left: 10px" @click="handleReset">{{ $t('mall.reset') }}</el-button>
    </div>
    <Table
      :columns="columns"
      :data="data.list"
      :total="data.total"
      :pageSize="data.pageSize"
      :pageNum="data.pageNum"
      :orderStatusObj="data.orderStatusObj"
      :serialOptions="{
        pageNum: data.pageNumber,
        pageSize: data.pageSize,
      }"
      @openprogressDialogVisible="openprogressDialogVisible"
      @openSmtWaitingMailingModel="openSmtWaitingMailingModel"
      @openPcbWaitingMailingModel="openPcbWaitingMailingModel"
    >
      <template #btnSlot="{ scope }">
        <div>
          <div class="m-b-5">
            <el-button size="small" type="warning" @click="checkDetails(scope.row)">{{
              $t('om.ViewDetails')
            }}</el-button>
          </div>
          <div class="m-b-5">
            <el-button
              size="small"
              v-if="scope.row.orderStatus == 2"
              type="primary"
              @click="payment(scope.row)"
              style="min-width: 74px"
            >
              {{ $t('om.Pay') }}
            </el-button>
          </div>
          <div class="m-b-5">
            <el-button
              size="small"
              v-if="[0, 2].includes(scope.row.orderStatus)"
              type="danger"
              @click="openOder(scope.row)"
              >{{ $t('om.CancelOrder') }}</el-button
            >
          </div>
          <div class="m-b-5">
            <el-button
              size="small"
              type="danger"
              v-if="[3, 4, 5, 6, 7].includes(scope.row.orderStatus)"
              @click="payment(scope.row)"
              style="min-width: 74px"
            >
              {{ $t('mall.refund') }}</el-button
            >
          </div>
          <div class="m-b-5">
            <el-button
              size="small"
              type="danger"
              v-if="[11].includes(scope.row.orderStatus)"
              @click="deleteOrder(scope.row)"
              style="min-width: 74px"
            >
              {{ $t('smt.Deleting') }}</el-button
            >
          </div>
          <el-button
            v-if="scope.row.orderStatus === 1"
            type="warning"
            size="small"
            @click.prevent="confirmBom(scope.row)"
          >
            {{ $t('mall.confirm') }} BOM
          </el-button>
        </div>
      </template>
    </Table>
    <Pagination
      class="right-align"
      v-show="data.total > 0"
      :total="data.total"
      v-model:page="data.pageNumber"
      v-model:limit="data.pageSize"
      @pagination="handlePaginationChange"
    />
  </div>
  <el-dialog
    v-model="data.dialogVisible"
    :title="$t('om.CancelOrder')"
    center
    width="30%"
    :before-close="handleClose"
  >
    <span>{{ $t('mall.confirm_cancel_order') }}?</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.dialogVisible = false">{{ $t('om.Cancel') }}</el-button>
        <el-button type="primary" @click="cancelOrder">{{ $t('smt.Define') }} </el-button>
      </span>
    </template>
  </el-dialog>
  <ProgressFollowUp
    v-if="data.orderProgressOptions && data.progressStatus"
    v-model="data.progressDialogVisible"
    :progressStatus="data.progressStatus"
    :orderProgressOptions="data.orderProgressOptions"
    @handleClose="handleClose"
  />
  <PcbWaitingMailingModel
    v-model="data.pcbVisible"
    :pcbInfo="data.pcbInfo"
    @closePcbWaitingMailingModel="closePcbWaitingMailingModel"
    @goToMail="goToMail"
    ref="pcbRef"
  />
  <SmtWaitingMailingModel
    v-model="data.smtVisible"
    :smtInfo="data.smtInfo"
    @closeSmtWaitingMailingModel="closeSmtWaitingMailingModel"
    @goToMail="goToMail"
    ref="bomRef"
  />
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import Table from '@/components/Table/index.vue';
import {
  getPcbSmtList,
  getDictList,
  cancelOrderById,
  inquireFile,
  deleteOrderById,
} from '@/server/api/biz.js';
import Pagination from '@/components/Pagination/index.vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import ProgressFollowUp from '@/views/order/components/ProgressFollowUp.vue';
import PcbWaitingMailingModel from '../components/PcbWaitingMailingModel.vue';
import SmtWaitingMailingModel from '../components/SmtWaitingMailingModel.vue';
import { useI18n } from 'vue-i18n';
const dateRange = ref([]);
const { t } = useI18n();
const emit = defineEmits(['getRuoterInfo']);
const columns = computed(() => [
  {
    label: t('om.OrderNo'),
    prop: 'serial',
  },
  {
    label: t('om.OrderInfo'),
    prop: 'items',
    width: '250',
  },
  {
    label: t('om.Timeoforder'),
    prop: 'createTime',
  },
  // {
  //   label: t('om.Postal'),
  //   prop: 'mails',
  // },
  {
    label: t('om.Estimateddelivery'),
    prop: 'deliveryDay',
    width: '160',
  },
  {
    label: t('om.Prices'),
    width: '100',
    prop: 'payCurrencyTaxAmount',
  },
  {
    label: t('om.OrderStatus'),
    fixed: 'right',
    prop: 'orderStatus',
  },
  {
    label: t('om.OrderOperation'),
    fixed: 'right',
    type: 'btn',
  },
]);
const router = useRouter();
const data = reactive({
  serial: '', //订单编号
  startDate: '',
  endDate: '',
  orderType: '',
  orderStatus: '',
  list: [],
  total: 0,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  orderTypeOptions: [],
  orderStatusOptions: [],
  orderStatusObj: {},
  orderProgressOptions: [],
  progressStatus: 0,
  progressDialogVisible: false,
  orderId: 0,
  pcbVisible: false,
  smtVisible: false,
  smtInfo: {},
  pcbInfo: {},
});
const bomRef = ref(null);
const pcbRef = ref(null);

const goToMail = () => {
  console.log('跳转');
  // router.push({ query: { type: 1, tabs: 1, recordType: 2 } });
  emit('getRuoterInfo');
};

const openSmtWaitingMailingModel = (row, type) => {
  data.smtVisible = true;
  data.smtInfo = row;
  bomRef.value.getBomlist(1, 10, row.id);
};

const openPcbWaitingMailingModel = (row) => {
  data.pcbVisible = true;
  data.pcbInfo = row;
  pcbRef.value.getQueryPcbaPcbOrderList(1, 10, row.id);
};

const closePcbWaitingMailingModel = () => {
  console.log('关闭');
  data.pcbVisible = false;
};

const closeSmtWaitingMailingModel = () => {
  data.smtVisible = false;
};

/**
 * 获取列表数据
 * @param {*} page
 * @param {*} limit
 */
const getList = (page = 1, limit = 10) => {
  const [startTime = '', endTime = ''] = dateRange.value || [];
  const obj = {
    limit,
    orderCategory: 2, // 订单类别 1pcb,2pcba,3成品
    orderStatus: data.orderStatus,
    page,
    serial: data.serial,
    endTime: endTime ? `${endTime} 23:59:59` : '',
    startTime: startTime ? `${startTime} 00:00:00` : '',
  };
  getPcbSmtList(obj).then((res) => {
    if (res.code === 200) {
      data.list = res.data.list;
      data.total = res.data.totalRow;
      data.pageNum = res.data.pageNumber;
      data.pageSize = res.data.pageSize;
    }
  });
};

onMounted(() => {
  getList();
  getDict();
});

const handleReset = () => {
  dateRange.value = [];
  data.orderStatus = null;
  data.serial = null;
  getList();
};

// 确认BOM
const confirmBom = async (row) => {
  const {
    bomFileId,
    id,
    crmPcbaSmtOrder: { smtNumber },
  } = row;

  const { code, msg, data } = await inquireFile(row.bomFileId);
  if (code !== 200) {
    ElMessage.error(msg);
    return;
  }
  let fileSerial = '';
  let bomName = '';
  if (data) {
    fileSerial = data.fileSerial;
    bomName = data.fileName;
  }
  router.push({
    path: '/quotation',
    query: {
      bomName,
      fileSerial,
      patchNum: smtNumber,
      bomFileId,
      bomConfirmShow: 1,
      orderListType: 1,
      id,
      beforeOrderType: 'smtOrderList',
    },
  });
};

/**
 * 接收当前列数据
 * @param {*} row
 */
const openprogressDialogVisible = (row) => {
  data.progressStatus = row.orderProgress;
  const status = {
    8: t('mall.complete'),
    9: t('mall.refund'),
    10: t('mall.refund'),
    11: t('smt.Cancel'),
  };
  data.orderProgressOptions = data.orderProgressOptions.splice(0, 6);
  const index = data.orderProgressOptions.findIndex((item) => item.value === '2');

  if (!row.orderStatus) {
    data.orderProgressOptions[index].label = `${t('mall.match')} ${t('mall.estimated_time')}`;
  } else {
    data.orderProgressOptions[index].label = t('mall.match');
  }
  if (status[row.orderStatus]) {
    // 匹配到添加，元素
    data.orderProgressOptions.push({
      value: '7',
      label: status[row.orderStatus],
    });
  } else {
    // 没找到，默认为完成
    data.orderProgressOptions.push({
      value: '7',
      label: t('mall.complete'),
    });
  }
  data.progressDialogVisible = true;
};

const handleClose = () => {
  data.dialogVisible = false;
  data.progressStatus = 0;
};

/**
 * 打开获取订单ID
 * @param {*} row
 */
const openOder = (row) => {
  data.dialogVisible = true;
  data.orderId = row.id;
};

/**
 * 取消订单
 */
const cancelOrder = () => {
  cancelOrderById(data.orderId).then((res) => {
    if (res.code === 200) {
      ElMessage.success(t('mall.cancel_success'));
      data.dialogVisible = false;
      getList();
    } else {
      ElMessage.error(res.msg);
    }
  });

  data.dialogVisible = false;
};

// 删除订单
const deleteOrder = (row) => {
  ElMessageBox.confirm(t('mall.confirm_delete', { name: row.serial }), t('coommon.tips'), {
    confirmButtonText: t('smt.Define'),
    cancelButtonText: t('smt.Cancel'),
    type: 'warning',
  }).then(async () => {
    const { code, msg } = await deleteOrderById(row.id);
    if (code === 200) {
      ElMessage.success(msg);
      getList();
    }
  });
};

/**
 * 获取字典状态列表
 */
const getDict = () => {
  getDictList().then((res) => {
    if (res.code === 200) {
      data.orderStatusObj = res.data.orderStatus;
      data.orderTypeOptions = setObjectToArray(res.data.orderQuoteType);
      data.orderStatusOptions = setObjectToArray(res.data.orderStatus);
      data.orderProgressOptions = setObjectToArray(res.data.orderProgress).splice(0, 7);
      console.log('data.orderProgressOptions', data.orderProgressOptions);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 对象转数组
 * @param {*} obj
 */
const setObjectToArray = (obj) => {
  const arr = [];
  for (const key in obj) {
    arr.push({
      value: key,
      label: obj[key],
    });
  }
  return arr;
};

/**
 * 分页
 */
const handlePaginationChange = (page = 1, limit = 10) => {
  console.log(page, limit);
  data.pageNum = page;
  data.pageSize = limit;
  getList(page, limit);
};

/**
 * 搜索列表
 */
const inquireOrderData = () => {
  getList();
};

/**
 * 查看详情
 */
const checkDetails = (row) => {
  console.log(row);
  router.push({
    path: '/orderDetail',
    query: {
      id: row.id,
      tabs: 0,
    },
  });
};

const payment = (row) => {
  router.push({
    path: 'payment',
    query: {
      id: row.id,
    },
  });
};
</script>
<style lang="scss" scope>
.el-button + .el-button {
  // margin-left: 0px;
  // margin: 5px 0px;
}
.el-date-editor {
  width: 130px !important;
}
.m-r-15 {
  margin-right: 15px;
}
.m-l-15 {
  margin-left: 15px;
}
.m-b-5 {
  margin-bottom: 5px;
}
.solid {
  width: 16px;
  height: 2px;
  border-radius: 2px;
  opacity: 1;
  background: #cccccc;
  margin-right: 16px;
  margin-left: 16px;
}
.inquire {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  margin-top: 10px;
}
.right-align {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
